package cn.lexi.vip.config.security;

import cn.lexi.vip.Constants;
import cn.lexi.vip.model.JsonResult;
import org.apache.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Aaron
 */
public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final String UNAUTHORIZED_RESULT = Constants.GSON.toJson(new JsonResult("UnAuthorized request", 401L, null));

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);

        httpServletResponse.setContentType("application/javascript; charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.println(UNAUTHORIZED_RESULT);
        out.close();
    }
}
